import os
import Image,ImageDraw
import ImageFilter
import ImageOps
import ImageFont
from psn_django import *
import urllib2
import subprocess

def removeNonAscii(s): return "".join(i for i in s if ord(i)<128)

def borda_texto(font, draw, x ,y, text, border_color="black"):
	# thicker border
	#textSize = draw.textsize(text, font=font)
	#textSize = (textSize[0]+x, textSize[1]+y)
	#draw.rectangle([(x,y), textSize], fill=(15,15,15))
	draw.text((x-1, y-1), text, font=font, fill=border_color)
	draw.text((x+1, y-1), text, font=font, fill=border_color)
	draw.text((x-1, y+1), text, font=font, fill=border_color)
	draw.text((x+1, y+1), text, font=font, fill=border_color)

def gen_psn_card_ht(user_db, user_last_trophy_db):
	font_path = 'tahoma.ttf'
	size_trophy = 15, 15

	img  = Image.new("RGB", (358,32), "#151515")
	draw = ImageDraw.Draw(img)

	# -- BG
	# Fundo
	if (user_trophy_db.user.card_bg_type == 1):
		if len(user_last_plat_db) is not 0:
			trophy = user_last_plat_db[0]
		else:
			trophy = user_last_trophy_db[0]
	else:
		trophy = user_last_trophy_db[0]

	bg = "./www/media/game/" + trophy.trophy.game.psn_id + "/card.png"

	if not os.path.exists(bg):
		bg = "./www/media/game/" + trophy.trophy.game.psn_id + "/icon.png"

	im_bg = Image.open(bg)

	# Ajusta o bg e cola na imagem final
	im_bg = ImageOps.fit(im_bg, (358,138), method=Image.ANTIALIAS, centering=(0.8,0.8))
	#try:
	#	img.paste(im_bg, (0, 0), im_bg)
		#img.paste(im_bg, (140, 20), im_bg)
	#except:
	#	print "Bag bd"
		#img.paste(im_bg, (150, 30))
	img.paste(im_bg, (0, 0))

	# Trofeus
	im_plat   = Image.open("./www/media/platinum.png")
	im_gold   = Image.open("./www/media/gold.png")
	im_silver = Image.open("./www/media/silver.png")
	im_bronze = Image.open("./www/media/bronze.png")

	# Estrela do lvl
	im_level = Image.open("./www/media/level.png")

	im_plat.thumbnail(size_trophy,Image.ANTIALIAS)
	im_gold.thumbnail(size_trophy,Image.ANTIALIAS)
	im_silver.thumbnail(size_trophy,Image.ANTIALIAS)
	im_bronze.thumbnail(size_trophy,Image.ANTIALIAS)
	im_level.thumbnail(size_trophy,Image.ANTIALIAS)

	# Pinta os trofeus
	font = ImageFont.truetype(font_path, 12) 
	rank = str(user_db.rank)
	borda_texto(font, draw, 180, 2, "Rank", border_color="black")
	draw.text((180, 2), "Rank", font=font)
	borda_texto(font, draw, 180, size_trophy[0]+2, rank, border_color="black")
	draw.text((180, size_trophy[0]+2), rank, font=font, fill=(255,255,255))

	img.paste(im_level, (210, 2), im_level)
	borda_texto(font, draw, 211, size_trophy[0]+2, str(user_db.level), border_color="black")
	draw.text((211, size_trophy[0]+2), str(user_db.level), font=font, fill=(255,255,255))

	img.paste(im_plat  , (240, 2) , im_plat)
	borda_texto(font, draw, 241, size_trophy[0]+2, str(user_db.platinum), border_color="black")
	draw.text((241, size_trophy[0]+2), str(user_db.platinum), font=font, fill=(255,255,255))

	img.paste(im_gold  , (270, 2), im_gold)
	borda_texto(font, draw, 272, size_trophy[0]+2, str(user_db.gold), border_color="black")
	draw.text((272, size_trophy[0]+2), str(user_db.gold), font=font, fill=(255,255,255))

	img.paste(im_silver, (300, 2), im_silver)
	borda_texto(font, draw, 301, size_trophy[0]+2, str(user_db.silver), border_color="black")
	draw.text((301, size_trophy[0]+2), str(user_db.silver), font=font, fill=(255,255,255))

	img.paste(im_bronze, (330, 2), im_bronze)
	borda_texto(font, draw, 331, size_trophy[0]+2, str(user_db.bronze), border_color="black")
	draw.text((331, size_trophy[0]+2), str(user_db.bronze), font=font, fill=(255,255,255))


	# --- baixando
	file_name = "/tmp/avatar.png"
	im_avatar = Image.open(file_name)
	im_avatar.thumbnail((32,32),Image.ANTIALIAS)
	img.paste(im_avatar, (0, 0), im_avatar)

	# Nome do safado
	font = ImageFont.truetype(font_path, 20) 
	borda_texto(font, draw, 35, 2, user_db.user.auth.username, border_color="black")
	draw.text((35, 2), user_db.user.auth.username, font=font, fill=(255,255,255))

	out_name = "./www/media/card/" + user_db.user.auth.username + "-ht.jpg"
	img = ImageOps.expand(img,border=1,fill='gray')
	img = ImageOps.expand(img,border=1,fill='black')
	img.save(out_name, "JPEG")
	url = "http://myps3t.dyndns.org:8000/media/card/" + user_db.user.auth.username + "-ht.jpg"
	subprocess.call(['chown', 'apache:', '/home/fabriciols/ps3t/myps3t/www/media/card/%s-ht.jpg' %user_trophy_db.user.auth.username])
	print url

def gen_psn_card(user_db, user_last_trophy_db, user_last_plat_db):

	#font_path = '/usr/share/fonts/bitstream-vera/VeraIt.ttf'
	font_path = 'tahoma.ttf'

	# O cartao em si
	img  = Image.new("RGBA", (358,138), "#151515")
	draw = ImageDraw.Draw(img)

	# Estas sao as partes transparentes
	img2  = Image.new("RGBA", (358,35), "#151515")
	draw2 = ImageDraw.Draw(img2)

	# Transparencia que fica atras dos ultimos trofeus
	img3  = Image.new("RGBA", (130,68), "#000")
	draw3 = ImageDraw.Draw(img3)
	draw3.rectangle((0, 0, 130, 68)   , fill=(10,10,60,100))

	# Tamanho dos icones dos trofeus
	size_trophy = 15, 15

	# Fundo
	if (user_trophy_db.user.card_bg_type == 1):
		if len(user_last_plat_db) is not 0:
			trophy = user_last_plat_db[0]
		else:
			trophy = user_last_trophy_db[0]
	else:
		trophy = user_last_trophy_db[0]

	bg = "./www/media/game/" + trophy.trophy.game.psn_id + "/card.png"

	if not os.path.exists(bg):
		bg = "./www/media/game/" + trophy.trophy.game.psn_id + "/icon.png"


	im_bg = Image.open(bg)

	# Ajusta o bg e cola na imagem final
	im_bg = ImageOps.fit(im_bg, (358,138), method=Image.ANTIALIAS)
	#try:
	#	img.paste(im_bg, (0, 0), im_bg)
		#img.paste(im_bg, (140, 20), im_bg)
	#except:
	#	print "Bag bd"
		#img.paste(im_bg, (150, 30))
	img.paste(im_bg, (0, 0))

	# Trofeus
	im_plat   = Image.open("./www/media/platinum.png")
	im_gold   = Image.open("./www/media/gold.png")
	im_silver = Image.open("./www/media/silver.png")
	im_bronze = Image.open("./www/media/bronze.png")

	# Estrela do lvl
	im_level = Image.open("./www/media/level.png")

	im_plat.thumbnail(size_trophy,Image.ANTIALIAS)
	im_gold.thumbnail(size_trophy,Image.ANTIALIAS)
	im_silver.thumbnail(size_trophy,Image.ANTIALIAS)
	im_bronze.thumbnail(size_trophy,Image.ANTIALIAS)
	im_level.thumbnail((20,20),Image.ANTIALIAS)

	# Pinta as partes transparentes (em cima e embaixo)
	draw2.rectangle((0, 0, 358, 35)   , fill=(0,0,0,100))
	img2 = ImageOps.expand(img2,border=1,fill=(255,255,255,50))
	img.paste(img2, (0, 0), img2)
	#img.paste(img2, (0, 125), img2)
	#img.paste(img3, (8, 46), img3)

	# Pinta os trofeus
	START_LEVEL=200
	img.paste(im_level, (START_LEVEL, 2), im_level)
	font = ImageFont.truetype(font_path, 15) 
	borda_texto(font, draw, START_LEVEL+20, 2, str(user_db.level))
	draw.text((START_LEVEL+20, 2), str(user_db.level), font=font, fill=(255,255,255))

	font = ImageFont.truetype(font_path, 10) 
	text = " %d%%" %user_db.perc_level
	size_more = draw.textsize(str(user_db.level))
	borda_texto(font, draw, START_LEVEL+25+size_more[0], 7, text)
	draw.text((START_LEVEL+25+size_more[0], 7), text, font=font, fill=(255,255,255))

	# Printa a quantidade do lvl
	font = ImageFont.truetype(font_path, 15) 
	img_perc  = Image.new("RGBA", (60,5), "#151515")
	draw_perc = ImageDraw.Draw(img_perc)
	draw_perc.rectangle((0, 0, (user_db.perc_level / 1.6), 5), fill=(255,255,255,250))
	img_perc  = ImageOps.expand(img_perc,border=1,fill='white')
	img.paste(img_perc  , (START_LEVEL, 25))

	font = ImageFont.truetype(font_path, 12) 

	img.paste(im_plat  , (270, 18) , im_plat)
	borda_texto(font, draw, 270+size_trophy[0], 18, str(user_db.platinum))
	draw.text((270+size_trophy[0], 18), str(user_db.platinum), font=font, fill=(255,255,255))

	img.paste(im_gold  , (270, 2), im_gold)
	borda_texto(font, draw, 270+size_trophy[0], 2, str(user_db.gold))
	draw.text((270+size_trophy[0], 2), str(user_db.gold), font=font, fill=(255,255,255))

	img.paste(im_silver, (315, 18), im_silver)
	borda_texto(font, draw, 315+size_trophy[0], 18, str(user_db.silver))
	draw.text((315+size_trophy[0], 18), str(user_db.silver), font=font, fill=(255,255,255))

	img.paste(im_bronze, (315, 2), im_bronze)
	borda_texto(font, draw, 315+size_trophy[0], 2, str(user_db.bronze))
	draw.text((315+size_trophy[0], 2), str(user_db.bronze), font=font, fill=(255,255,255))

	# Pinta os ultimos trofeus conquistados
	size_start = (10,48)
	i = 0

	if (user_trophy_db.user.card_last_trophy == 1):
		for trophy in user_last_trophy_db:
			# Estas sao as partes transparentes
			imgt  = Image.new("RGBA", (33,33), "#000")
			drawt = ImageDraw.Draw(imgt)
			drawt.rectangle((1, 1, 32, 32)   , fill=(0,0,0,100))

			trophy_pic = "./www/media/game/" + trophy.trophy.game.psn_id + "/" + trophy.trophy.pic_url
			try:
				im_trophy = Image.open(trophy_pic)
			except:
				print "Cant find %s" %trophy_pic
				continue

			im_trophy.thumbnail((30,30),Image.ANTIALIAS)
			try:
				imgt.paste(im_trophy, (2, 2), im_trophy)
			except:
				print "Error in pic"
				print trophy_pic
				imgt.paste(im_trophy, (2, 2))

			img.paste(imgt, size_start, imgt)

			if i == 3:
				size_start = (size_start[0] - 34*i, size_start[1] + 34)
			else:
				size_start = (size_start[0] + 34, size_start[1])
			i += 1

	# Avatar e nome do nego
	# --- baixando
	file_name = "/tmp/avatar.png"
	req = urllib2.Request(user_db.user.pic_url)
	f = urllib2.urlopen(req)
	local_file = open(file_name, "wb")
	local_file.write(f.read())
	local_file.close()
	im_avatar = Image.open(file_name)

	im_avatar.thumbnail((30,30),Image.ANTIALIAS)
	img.paste(im_avatar, (0, 0), im_avatar)

	# Nome do safado
	font = ImageFont.truetype(font_path, 20) 
	borda_texto(font, draw, 35, 2, user_db.user.auth.username)
	draw.text((35, 2), user_db.user.auth.username, font=font, fill=(255,255,255))

	# Printa em baixo o nome do site
	font = ImageFont.truetype(font_path, 10) 

	# --- BORDA
	# thin border
	text="myPS3t"
	borda_texto(font, draw, 323, 125, text)
	# --- Texto
	draw.text((323, 125), text, font=font, fill=(255,255,255))

	rank = "Rank: " + str(user_db.rank)
	borda_texto(font, draw, 1, 125, rank)
	draw.text((2, 125), rank, font=font, fill=(255,255,255))

	#img = ImageOps.expand(img,border=1,fill='gray')
	img = ImageOps.expand(img,border=1,fill=(255,255,255,50))
	img = ImageOps.expand(img,border=1,fill='black')

	out_name = "./www/media/card/" + user_db.user.auth.username + ".png"
	url = "http://myps3t.dyndns.org:8000/media/card/" + user_db.user.auth.username + ".png"
	print url
	img.save(out_name, "PNG")

def gen_hall_plat(user_db, user_last_plat_db):


	len_plat = len(user_last_plat_db)

	text="%s" %user_db.user.auth.username

	if len_plat is not 0:

		if (len_plat >= 10):
			x = 400
		else:
			x = 40*len_plat

		if (x < len(text)*8):
			x = len(text)*8

		if (x < 400):
			x+= 90

		y = (len_plat / 10)

		if (len_plat % 10 > 0):
			y += 1

		if y == 0:
			y = 1

		y *= 40

		size = x,y+40

		img  = Image.new("RGB", size, "#151515")
		draw = ImageDraw.Draw(img)

		# Fundo
		trophy = user_last_plat_db[0]

		bg = "./www/media/game/" + trophy.trophy.game.psn_id + "/card.png"

		if not os.path.exists(bg):
			bg = "./www/media/game/" + trophy.trophy.game.psn_id + "/icon.png"

		print bg
		im_bg = Image.open(bg)

		# Ajusta o bg e cola na imagem final
		im_bg = ImageOps.fit(im_bg, size, method=Image.ANTIALIAS)
		img.paste(im_bg, (0, 0))

		# Estas sao as partes transparentes
		img2  = Image.new("RGBA", (x,30), "#cdcdcd")
		draw2 = ImageDraw.Draw(img2)

		draw2.rectangle((0, 0, x, 30) , fill=(0,0,0,160))
		img2 = ImageOps.expand(img2,border=1,fill=(255,255,255,50))

		font_path = "tahoma.ttf"
		font = ImageFont.truetype(font_path, 16)

		size_trophy = 28,28
		textSize = draw.textsize(text, font=font)
		im_plat   = Image.open("./www/media/platinum.png")
		im_plat.thumbnail(size_trophy,Image.ANTIALIAS)
		img2.paste(im_plat, (textSize[0]+size_trophy[0]+10, 2), im_plat)

		img.paste(img2, (0, 0), img2)
		draw.text((35, 3), text, font=font)

		size_start = (5,35)
		i = 0

		# --- baixando
		file_name = "/tmp/avatar.png"
		im_avatar = Image.open(file_name)
		im_avatar.thumbnail((32,32),Image.ANTIALIAS)
		img.paste(im_avatar, (0, 0), im_avatar)

		for trophy in user_last_plat_db:
			# Estas sao as partes transparentes
			imgt  = Image.new("RGBA", (40,40), "#000")
			drawt = ImageDraw.Draw(imgt)
			drawt.rectangle((1, 1, 40, 40)   , fill=(0,0,0,100))

			trophy_pic = "./www/media/game/" + trophy.trophy.game.psn_id + "/" + trophy.trophy.pic_url
			im_trophy = Image.open(trophy_pic)
			im_trophy.thumbnail((38,38),Image.ANTIALIAS)

			try:
				imgt.paste(im_trophy, (2, 2), im_trophy)
			except:
				print "Error in pic"
				print trophy_pic
				imgt.paste(im_trophy, (2, 2))

			img.paste(imgt, size_start, imgt)

			if i == 9:
				size_start = (size_start[0] - 38*i, size_start[1] + 38)
				i = -1
			else:
				size_start = (size_start[0] + 38, size_start[1])

			i += 1

		img = ImageOps.expand(img,border=1,fill=(255,255,255,50))
		img = ImageOps.expand(img,border=1,fill=(0,0,0,50))
		out_name = "./www/media/card/" + user_trophy_db.user.auth.username + "-hall.png"
		url = "http://myps3t.dyndns.org:8000/media/card/" + user_trophy_db.user.auth.username + "-hall.png"
		print url
		img.save(out_name, "PNG")

		subprocess.call(['chown', 'apache:', '/home/fabriciols/ps3t/myps3t/www/media/card/%s-hall.png' %user_trophy_db.user.auth.username])

if __name__ == "__main__":

	if len(sys.argv) is 2:
		users = db.userTrophy.objects.filter(user__auth__username=sys.argv[1])
	else:
		users = db.userTrophy.objects.filter(user__card = 1)

	for user_trophy_db in users:

		file_name = "/tmp/avatar.png"
		req = urllib2.Request(user_trophy_db.user.pic_url)
		f = urllib2.urlopen(req)
		local_file = open(file_name, "wb")
		local_file.write(f.read())
		local_file.close()

		print "Generating card for: %s" %user_trophy_db.user.auth.username

		user_last_trophy_db = db.gameUserTrophyInfo.objects.filter(user=user_trophy_db.user).order_by('-date')
		user_last_trophy_db = user_last_trophy_db.exclude(trophy__type="hidden")
		user_last_plat_db   = user_last_trophy_db.filter(trophy__type="platinum")
		user_last_trophy_db = user_last_trophy_db.exclude(trophy__pic_url="hidden.png")[:8]

		gen_psn_card(user_trophy_db, user_last_trophy_db, user_last_plat_db)
		gen_psn_card_ht(user_trophy_db, user_last_trophy_db)
		gen_hall_plat(user_trophy_db, user_last_plat_db)
		subprocess.call(['chown', 'apache:', '/home/fabriciols/ps3t/myps3t/www/media/card/%s.png' %user_trophy_db.user.auth.username])

		os.remove(file_name)


	
